package com.buba.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

/**
 *  用来整合shiro框架相关的配置类
 *
 * @Author: 游王子
 * @date: 2021/8/20 16:22
 */
@SpringBootConfiguration
public class SpringConfig {
    /**
     * 方法描述 自定义领域 （包含了验证和授权）
     *   解密
     * @param
     * @author:
     * @return: com.buba.config.CustomRealm
     * @date: 2021/8/20
     */
    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm = new CustomRealm();
        // 添加认证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        // 设置加密算法名字
        matcher.setHashAlgorithmName("MD5");
        // 设置迭代次数
        matcher.setHashIterations(1);
        customRealm.setCredentialsMatcher(matcher);
        return customRealm;
    }

    /**
     * 方法描述 默认的shiro web安全管理器
     *
     * @param
     * @author:
     * @return: org.apache.shiro.web.mgt.DefaultWebSecurityManager
     * @date: 2021/8/20
     */
    @Bean
    public DefaultWebSecurityManager getDefaultSecurityManager() {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        // 向安全管理器中添加领域
        defaultSecurityManager.setRealm(customRealm());
        return defaultSecurityManager;
    }

    /**
     * 方法描述 定义默认shiro过滤链
     * 配置受限资源和公共资源
     * @author:
     * @param
     * @return: org.apache.shiro.spring.web.config.ShiroFilterChainDefinition
     * @date: 2021/8/23
     */
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        // 定义默认shiro过滤链
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        // 主要定义匿名访问的路径  anon表示可以匿名访问路径
        definition.addPathDefinition("/login.html","anon");
        definition.addPathDefinition("/register.html","anon");
        definition.addPathDefinition("/UserController/login","anon");
        definition.addPathDefinition("/UserController/register","anon");
        definition.addPathDefinition("/style/**","anon");
        // 定义哪些资源需要认证才能访问 authc 表示需要认证
        definition.addPathDefinition("/**","authc");
        return definition;
    }
}
